<template>
  <el-dialog :close-on-click-modal="false" title="密码重置" width="9.259259rem" :visible.sync="visible" :before-close="handleClose">
    <el-form
      class="px-5"
      autocomplete="on"
      :model="ruleForm"
      element-loading-text="给我一点时间"
      v-loading="loading"
      :rules="rules"
      label-position="right"
      ref="ruleFormRef">
      <el-form-item label="密码：" prop="password">
        <el-input v-model="ruleForm.password" type="password" placeholder="请输入" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="确认密码：" prop="checkPassword">
        <el-input v-model="ruleForm.checkPassword" type="password" placeholder="请输入" maxlength="20"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {resetPasswordUser} from 'api/admin-user'
import { toEncrypt } from '@/utils'
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    id: {
      type: Number,
      required: true
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      ruleForm: {
        password: '',
        checkPassword: ''
      },
      // 表单验证
      rules:{
        password:[
          {required:true,trigger:'blur',message:'请输入密码'},
          { validator: validatePassword, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, trigger: 'blur', validator: validatePass }
        ]
      },
    }
  },
  methods: {
    onConfirm() {
      this.$refs['ruleFormRef'].validate(valid => {
        if(valid) {
          this.loading = true
          const json = JSON.parse(JSON.stringify(this.ruleForm))
          json.password = toEncrypt(json.password)
          resetPasswordUser(this.id, {password: json.password}).then(() => {
            this.$message.success('操作成功')
            this.loading = false
            this.handleClose()
            this.$emit('getList')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    handleClose() {
      this.$refs.ruleFormRef.resetFields()
      this.$emit('update:visible', false)
    }
  }
}
</script>